import { Ref, useMemo, useRef, useState } from 'react';
import { IOneModalRef } from '../one-ui/OneModal/type';
import { OneModal } from '../one-ui';
import { Spin, Upload, UploadProps, message } from 'antd';
import { InboxOutlined } from '@ant-design/icons';
import { downloadTemplate, getFileNameByPath, getTenant, onCloseModalCommon } from '@/utils';
import { getBaseUrl } from '@/services/urlconst';
import './styles.less';
import { batchImportServices } from './services';
const baseUrl = getBaseUrl();

/**
 * @description 批量导入文件弹窗公共组件
 * @param {object} curRes - 权限对象
 * @param {string} modalTitle - 弹窗名称
 * @param {function} onClose - 关闭弹窗方法
 * @param {string} downloadTemplateUrl - 关闭弹窗方法
 * @param {string} templateUrl - 模板下载地址
 * @param {string} templateName - 模板文件名称
 * @param {string} parserImportUrl - 导入文件解析数据返回的请求地址
 * @param {string} batchImportUrl - 批量导入接口
 * @param {function} refreshCallback - 成功后的回调
 * @param {string} filePath - 文件地址
 * @param {object} parserReqHeader - 解析数据接口hearder参数
 * @param {object} batchReqHeader - 批量导入接口hearder参数
 * */
const BatchImportModal = ({
  curRes,
  modalTitle = '批量导入弹窗',
  onClose,
  templateUrl,
  parserImportUrl,
  batchImportUrl,
  refreshCallback,
  filePath,
  parserReqHeader = {},
  batchReqHeader = {},
}) => {
  /**
   * 样式类名
   * */
  const prefix = 'batch-importCpt-';

  /**
   * 弹框的ref
   * */
  const modalRef: Ref<IOneModalRef> = useRef(null);

  /**
   * 导入数据源
   * */
  const [batchData, setBatchData] = useState<Record<string, any>[]>([]);

  /**
   * loading
   * */
  const [upLoading, setUpLoading] = useState<boolean>(false);

  /**
   * 数据导入接口
   * */
  const { batchImportRun, batchImportLoading } = batchImportServices(batchImportUrl, batchReqHeader);

  /**
   * 关闭弹窗
   * */
  const onCloseModal = () => {
    onClose();
  };

  /**
   * 确定按钮
   * */
  const onOkModal = () => {
    if (batchData?.length) {
      batchImportRun(batchData)?.then((res) => {
        if (res?.msgFlag) {
          message?.success(res?.msg);
          onCloseModalCommon(modalRef);
          refreshCallback();
        }
      });
    } else {
      message?.warn('请检查文件是否正确！');
    }
  };

  /**
   * 点击下载模板
   * */
  const onDownloadTemplate = async () => {
    let fileName = getFileNameByPath(filePath);
    downloadTemplate(templateUrl, fileName, filePath, () => {});
  };

  /**
   * 上传配置
   * */
  const uploadProps: UploadProps = {
    accept: '.xls,.xlsx,.xlsm',
    headers: {
      tenantName: getTenant(),
      ...parserReqHeader,
    },
    name: 'attachFile',
    maxCount: 1,
    action: `${baseUrl}${parserImportUrl}`,
    onChange(info) {
      if (info.file.status == 'uploading') {
        setUpLoading(true);
      }
      if (info.file.status === 'done') {
        if (info.file?.response) {
          if (info.file?.response?.msgFlag) {
            message?.warn(info.file?.response?.msg);
            if (info.file?.response?.obj) {
              let data = info.file?.response?.obj;
              setBatchData(data);
            }
            setUpLoading(false);
          } else {
            message?.warn(info.file?.response?.msg);
            setUpLoading(false);
          }
        }
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`);
        setUpLoading(false);
      }
    },
    onRemove: (file) => setBatchData([]),
  };

  /**
   * loadingMemo
   * */
  const modalLoading = useMemo(() => {
    return upLoading || batchImportLoading;
  }, [upLoading, batchImportLoading]);

  return (
    <>
      <OneModal
        open={true}
        getContainer={false}
        ref={modalRef}
        title={modalTitle || '提示'}
        onCancel={onCloseModal}
        onOk={onOkModal}
        width={document.body.clientWidth * 0.35}
        bodyStyle={{ padding: '20px 40px', height: document.body.clientHeight * 0.25 }}
        confirmLoading={modalLoading}
        className={prefix + 'modalBox'}
      >
        <Spin spinning={modalLoading}>
          <div className={prefix + 'modalBox-uploadBox'}>
            <Upload.Dragger {...uploadProps}>
              <div style={{ height: 'auto' }}>
                <p>
                  <InboxOutlined />
                </p>
                <div>
                  将文件拖到此处，或&nbsp;
                  <span>点击上传</span>
                </div>
              </div>
            </Upload.Dragger>
          </div>

          {curRes?.[templateUrl] && (
            <div className={prefix + 'modalBox-downloadTips'}>
              • 文件格式保证正确（仅支持.xlsx .xls .xlsm文件）
              <a onClick={onDownloadTemplate}>下载模板</a>
            </div>
          )}
        </Spin>
      </OneModal>
    </>
  );
};

export { BatchImportModal };
